﻿// ———————————————————————–
// <copyright file="HistoryProcessing.cs" company="The MITRE Corporation">
//    Copyright (c) 2014 The MITRE Corporation. All rights reserved.
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// ———————————————————————–
/////////////////////////////////////////////////////////////////////////////////////////////////
// DEProcessing.cs - Service implementation that pulls DE messages from a SQS queue and writes
//                   them to DynamoDB for history purposes
// Project: EDXLSharp_AWSRouter- HistoryProcessing
//
// Language:    C#, .NET 4.0
// Platform:    Windows Server 2012, VS 2013
// Author:      Chris Hossenlopp The MITRE Corporation
/////////////////////////////////////////////////////////////////////////////////////////////////

// Copyright (c) 2014 The MITRE Corporation. All rights reserved.
//
// NOTICE
// This software was produced for the U. S. Government
// under Contract No. FA8721-09-C-0001, and is
// subject to the Rights in Noncommercial Computer Software
// and Noncommercial Computer Software Documentation Clause
// (DFARS) 252.227-7014 (JUN 1995)

using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Amazon.SQS;
using Amazon.SQS.Model;
using Amazon.Util;
using EDXLSharp.EDXLDELib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ICNETServices;
// Configure log4net using the .config file
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace HistoryProcessing
{
  /// <summary>
  /// Class for the History Processing Windows Service
  /// </summary>
  public partial class HistoryProcessing : ServiceBase
  {
    /// <summary>
    /// Log4net logging object
    /// </summary>
    private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    /// <summary>
    /// Thread to run the SQS polling on
    /// </summary>
    private Thread runThread;

    /// <summary>
    /// Amazon SQS configuration object 
    /// </summary>
    private AmazonSQSConfig amazonSQSConfig;

    /// <summary>
    /// Amazon SQS Client
    /// </summary>
    private AmazonSQSClient amazonSQSClient;

    /// <summary>
    /// Amazon DynamoDB configuration object
    /// </summary>
    private AmazonDynamoDBConfig amazonDynamoConfig;

    /// <summary>
    /// Amazon DynamoDB client
    /// </summary>
    private AmazonDynamoDBClient amazonDynamoClient;


    /// <summary>
    /// Initializes a new instance of the HistoryProcessing class
    /// </summary>
    public HistoryProcessing()
    {
      this.InitializeComponent();
      this.ServiceName = "History Service";
    }

    /// <summary>
    /// Method called when the service is started
    /// </summary>
    /// <param name="args">Command arguments (ignored)</param>
    protected override void OnStart(string[] args)
    {
      Log.Info("OnStart");
      try
      {
        this.amazonSQSConfig = new AmazonSQSConfig();
        this.amazonSQSConfig.ServiceURL = AWSConstants.SQSServiceURL;
        Log.DebugFormat("AWSConstants.SQSServiceURL = {0}", AWSConstants.SQSServiceURL);
        Log.DebugFormat("AWSConstants.HistoryProcessing.QueueName = {0}", AWSConstants.HistoryProcessing.QueueName);
        Log.DebugFormat("AWSConstants.HistoryProcessingQueueUrl = {0}", AWSConstants.HistoryProcessingQueueUrl);
        this.amazonSQSClient = new AmazonSQSClient(this.amazonSQSConfig);
        this.amazonDynamoConfig = new AmazonDynamoDBConfig();
        this.amazonDynamoConfig.ServiceURL = AWSConstants.DynamoServiceURL;
        this.amazonDynamoClient = new AmazonDynamoDBClient(this.amazonDynamoConfig);
      }
      catch (Exception e)
      {
        Log.Error("Failed to configure.", e);
        return;
      }

      this.runThread = new Thread(new ThreadStart(this.PollSQS));
      this.runThread.IsBackground = true;
      this.runThread.Start();
      Log.Info("OnStartComplete");
    }

    protected override void OnStop()
    {
      Log.Info("OnStop");
      if (this.runThread.IsAlive)
      {
        Log.Info("KillingThread");
        this.runThread.Abort();
        Log.Info("ThreadKilled");
      }
    }

    /// <summary>
    /// Thread worker method.
    /// </summary>
    private void PollSQS()
    {
      Log.Info("InThread");
      while (true)
      {
        Log.Info("SQSLoop");
        ReceiveMessageRequest req = new ReceiveMessageRequest();
        req.QueueUrl = AWSConstants.HistoryProcessingQueueUrl;
        req.WaitTimeSeconds = 20; // TODO make this a setting

        ReceiveMessageResponse resp = this.amazonSQSClient.ReceiveMessage(req);
        Log.Info("Got " + resp.Messages.Count + " messages from SQS");

        foreach (Message m in resp.Messages)
        {
          Log.Info(m.Body);
          EDXLDE de = new EDXLDE(m.Body);

          this.AddDEToHistory(de, m.Body);


          DeleteMessageRequest deleteMessageRequest = new DeleteMessageRequest();
          deleteMessageRequest.QueueUrl = req.QueueUrl;
          deleteMessageRequest.ReceiptHandle = m.ReceiptHandle;
          try
          {
            DeleteMessageResponse sqsdelresp = this.amazonSQSClient.DeleteMessage(deleteMessageRequest);
            if (sqsdelresp.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
              Log.Info("Message removed from queue");
            }
            else
            {
              Log.Error("SQS Delete error: " + sqsdelresp.HttpStatusCode.ToString());
            }
          }
          catch (Exception e)
          {
            Log.Error("Error deleting from SQS", e);
          }
        }
      }
    }

    /// <summary>
    /// Adds the DE message to the History table.
    /// </summary>
    /// <param name="de">The Distribution Element object that was received.</param>
    /// <param name="body">A string of the message body.</param>
    private void AddDEToHistory(EDXLDE de, string body)
    {
      PutItemRequest dynamoPutReq = new PutItemRequest();

      Dictionary<string, AttributeValue> dynamoItem = new Dictionary<string, AttributeValue>();
      dynamoItem.Add(AWSConstants.HistoryProcessing.DynamoInfo.HashName, new AttributeValue()
      {
        S = de.DistributionID
      });

      dynamoItem.Add(AWSConstants.HistoryProcessing.DynamoInfo.RangeName, new AttributeValue()
      {
        S = DateTime.Now.ToUniversalTime().ToString(AWSSDKUtils.ISO8601DateFormat)
      });

      dynamoItem.Add("senderID", new AttributeValue()
      {
        S = de.SenderID
      });

      dynamoItem.Add("dateTimeSent", new AttributeValue()
      {
        S = de.DateTimeSent.ToUniversalTime().ToString(AWSSDKUtils.ISO8601DateFormat)
      });

      dynamoItem.Add("EDXLDistribution", new AttributeValue()
      {
        S = body
      });
      dynamoPutReq.Item = dynamoItem;
      dynamoPutReq.TableName = AWSConstants.HistoryProcessing.DynamoInfo.TableName;
      try
      {
        PutItemResponse dynamoResp = this.amazonDynamoClient.PutItem(dynamoPutReq);
        if(dynamoResp.HttpStatusCode == System.Net.HttpStatusCode.OK)
        {
          Log.Info("Message Added to Dynamo History Table");
        }
        else
        {
          Log.Error("Dynamo Error" + dynamoResp.HttpStatusCode.ToString());
        }
      }
      catch (Exception e)
      {
        Log.Error("Error writing to DE to Dynamo History Table", e);
      }
    }
  }
}
